﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

using SharedGenomics.Domain;
using SharedGenomics.Workbench.Core;
using SharedGenomics.Workbench.Models;
using SharedGenomics.Core;

namespace SharedGenomics.Workbench.Views.WindowsForms
{
    public partial class AnalysisResultsView : View, IAnalysisResultsView
    {
        private IAnalysisResultsModel _model;
        private bool[] _annotationSetCompletedStatuses;

        public AnalysisResultsView()
        {
            InitializeComponent();
            this.ResultsGrid = new DataGrid<AnalysisResult>(this.dgvResults);
        }

        public event EventHandler ShowUcscBrowserClicked;
        public event EventHandler ShowPathwayFrequenciesClicked;
        public event EventHandler<ContextMenuRequiredEventArgs> ContextMenuRequired;

        public int[] SelectedResultIndices
        {
            get
            {
                return this.dgvResults.SelectedRows.Cast<DataGridViewRow>().Select(r => r.Index).ToArray();
            }
        }

        public IDataGrid<AnalysisResult> ResultsGrid { get; private set; }

        public IAnalysisResultsModel Model
        {
            set
            {
                value.ThrowIfNull("model");

                this._model = value;

                value.ResultsChanged += (o, e) => { 
                    this.ResultsGrid.Data = this._model.Results;
                    this.annotationSetStatusTimer.Enabled = true;
                    this.UpdateAnnotationSetCompletedStatuses();
                };
            }
        }

        private void btShowPathwayFrequencies_Click(object sender, EventArgs e)
        {
            this.ShowPathwayFrequenciesClicked.Raise(this);
        }

        private void btShowSelectedInUCSC_Click(object sender, EventArgs e)
        {
            this.ShowUcscBrowserClicked.Raise(this);
        }

        private void UpdateAnnotationSetCompletedStatuses()
        {
            this._annotationSetCompletedStatuses = this._model.GetResultAnnotationSetCompletedStatuses();
            this.dgvResults.Invalidate();
        }

        public int JobViewHeight
        {
            set { this.spcMain.SplitterDistance = value; }
        }

        private void grid_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (!e.ColumnIndex.IsBetween(0, this.dgvResults.Columns.Count - 1, true) ||  !e.RowIndex.IsBetween(0, this.dgvResults.Rows.Count-1, true))
                return;

            AnalysisResult ar = (AnalysisResult)this.dgvResults.Rows[e.RowIndex].DataBoundItem;
            bool isSnpColumn = (ar.GetSnpPropertyNames().Contains(this.dgvResults.Columns[e.ColumnIndex].DataPropertyName));

            if (isSnpColumn)
            {
                e.PaintBackground(e.ClipBounds, true);
                e.PaintContent(e.ClipBounds);

                int border = 5;
                Rectangle cellBounds = e.CellBounds;
                int markerSize = Math.Min(cellBounds.Width, cellBounds.Height) - (2 * border);
                Rectangle r = new Rectangle(
                    cellBounds.X + cellBounds.Width - markerSize - border,
                    cellBounds.Y + border,
                    markerSize,
                    markerSize);

                if (markerSize > 0)
                {
                    Color toColor = this.GetRowAnnotationSetStatusColour(e.RowIndex);

                    System.Drawing.Drawing2D.LinearGradientBrush brushPercent = new System.Drawing.Drawing2D.LinearGradientBrush(r, Color.White, toColor, System.Drawing.Drawing2D.LinearGradientMode.Vertical);
                    e.Graphics.FillRectangle(brushPercent, r);
                    e.Graphics.DrawRectangle(Pens.DimGray, r);
                    brushPercent.Dispose();
                }

                e.Handled = true;
            }
        }

        private Color GetRowAnnotationSetStatusColour(int rowIndex)
        {
            Debug.Assert(rowIndex.IsBetween(0, this.dgvResults.Rows.Count - 1, true));

            bool isAnnotationSetComplete =  this._annotationSetCompletedStatuses != null && 
                                            rowIndex.IsBetween(0, this._annotationSetCompletedStatuses.Length - 1, true) && 
                                            this._annotationSetCompletedStatuses[rowIndex];

            return isAnnotationSetComplete ? Color.DarkGreen : Color.DarkGoldenrod;
        }

        private void grid_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
        {
            this.dgvResults.CurrentCell = this.dgvResults[e.ColumnIndex, e.RowIndex];
            ContextMenuRequiredEventArgs ea = new ContextMenuRequiredEventArgs(e.RowIndex, e.ColumnIndex);
            this.ContextMenuRequired.Raise(this, ea);

            ContextMenuStrip contextMenu = ea.ContextMenu as ContextMenuStrip;
            if (contextMenu != null)
            {
                e.ContextMenuStrip = contextMenu;
            }
        }

        private void dgvResults_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            var propertyName = this.dgvResults.Columns[e.ColumnIndex].DataPropertyName;
            this._model.SortResultsByColumn(propertyName);
            this.UpdateAnnotationSetCompletedStatuses();
        }

        [Region("Jobs")]
        public Panel JobsPanel
        {
            get { return this.spcMain.Panel1; }
        }

        private void annotationSetStatusTimer_Tick(object sender, EventArgs e)
        {
            this.UpdateAnnotationSetCompletedStatuses();
        }
    }
}
